package servlet;

import dao.UserDAO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String captcha = request.getParameter("captcha");
        
        // 从 session 中获取生成的验证码
        String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
        request.getSession().removeAttribute("captcha"); // 避免重复使用
        
        if (sessionCaptcha == null || !captcha.equalsIgnoreCase(sessionCaptcha)) {
            request.setAttribute("error", "验证码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        if (UserDAO.validate(username, password)) {
            // 登录成功，保存用户信息到 session
            request.getSession().setAttribute("username", username);
            response.sendRedirect("admin.jsp"); // 跳转到后台管理页面
        } else {
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}
